package com.example.eduservice.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.common.commonsutils.R;
import com.example.common.exception.GuliException;
import com.example.eduservice.entity.EduSubject;
import com.example.eduservice.entity.ExcelSubjectData;
import com.example.eduservice.entity.vo.EduSubjectVO;
import com.example.eduservice.listener.ExcelSubjectDataListener;
import com.example.eduservice.mapper.EduSubjectMapper;
import com.example.eduservice.service.EduSubjectService;
import jakarta.annotation.Resource;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author:tjf
 * @Description:
 */
@Log4j2
@Service
public class EduSubjectServiceImpl extends ServiceImpl<EduSubjectMapper, EduSubject> implements EduSubjectService {
    @Resource
    private EduSubjectMapper subjectMapper;

    /**
     * 保存课程分类
     * @param file
     * @return
     */
    @Override
    public R saveSubjects(MultipartFile file) {
        try {
            EasyExcel.read(file.getInputStream(), ExcelSubjectData.class, new ExcelSubjectDataListener(subjectMapper)).sheet().doRead();
        }catch (GuliException e){
            throw e;
        }catch (Exception e){
            log.error(e.getMessage());
        }
        return R.ok();
    }

    /**
     * 获取课程分类列表
     * @return
     */
    @Override
    public List<EduSubjectVO> getSubjectList() {
        // 查询所有的课程分类
        List<EduSubject> allSubject = subjectMapper.selectList(null);
        // 对课程进行分类
        // 一级分类
        List<EduSubjectVO> oneSubjectList = this.getSubjectListByPid(allSubject, "0");
        // 二级分类
        for (EduSubjectVO oneSubject : oneSubjectList) {
            List<EduSubjectVO> twoSubjectList = this.getSubjectListByPid(allSubject, oneSubject.getId());
            oneSubject.setChildren(twoSubjectList);
        }
        return oneSubjectList;
    }

    /**
     * 根据pid，查询课程分类
     * @param allSubject
     * @param s
     * @return
     */
    private List<EduSubjectVO> getSubjectListByPid(List<EduSubject> allSubject, String s) {
        List<EduSubjectVO> result = new ArrayList<>();
        EduSubjectVO temp;
        if (allSubject != null && s != null){
            for (EduSubject eduSubject : allSubject) {
                if (s.equals(eduSubject.getParentId())){
                    temp = new EduSubjectVO();
                    // 属性赋值
                    BeanUtils.copyProperties(eduSubject, temp);
                    result.add(temp);
                }
            }
        }
        return result;
    }
}
